package cn.pugle.velocity;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * <p>
 *
 * @auther tzp on 2016/6/23.<br>
 */
public class TestTemplateEngine {
    public static void main(String[] args) {
        Properties p = new Properties();
        try {
            p.load(ClassLoader.getSystemResourceAsStream("velocity/velocity.properties"));
            Velocity.init(p);

            Template template = Velocity.getTemplate("velocity/table_structure.vm", "UTF-8");

            VelocityContext context = new VelocityContext();
            List<Map<String, Object>> tables = new ArrayList<>();
            //parse tables from sql
            String s = "CREATE TABLE `xx_access_token` (\n" +
                    "  `id` int(6) NOT NULL AUTO_INCREMENT,\n" +
                    "  `tenantId` int(4) NOT NULL,\n" +
                    "  `orgIds` varchar(50) NOT NULL,\n" +
                    "  `createdTime` datetime NOT NULL,\n" +
                    "  `revokedTime` datetime DEFAULT NULL,\n" +
                    "  `isRevoked` tinyint(4) NOT NULL DEFAULT '0',\n" +
                    "  `token` varchar(50) NOT NULL,\n" +
                    "  `qpsLimit` int(11) DEFAULT '5000',\n" +
                    "  `comment` varchar(200) DEFAULT NULL,\n" +
                    "  PRIMARY KEY (`id`)\n" +
                    ") ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;\n" +
                    "CREATE TABLE `xx_account` (\n" +
                    "  `AccountId` int(4) NOT NULL AUTO_INCREMENT COMMENT '主键，自增',\n" +
                    "  `RoleId` int(4) NOT NULL DEFAULT '0',\n" +
                    "  `Name` varchar(200) NOT NULL DEFAULT '',\n" +
                    "  `Password` varchar(200) NOT NULL DEFAULT '',\n" +
                    "  `Email` varchar(200) NOT NULL DEFAULT '',\n" +
                    "  `PhoneNo` varchar(100) NOT NULL DEFAULT '',\n" +
                    "  `IsDeleted` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除状态：0是未删除；1是删除',\n" +
                    "  `CreateDate` datetime NOT NULL DEFAULT '1970-01-01 08:00:00' COMMENT '创建时间',\n" +
                    "  `LoginDate` datetime NOT NULL DEFAULT '1970-01-01 08:00:00' COMMENT '最近登录时间',\n" +
                    "  `AdminFlag` char(1) NOT NULL DEFAULT '5' COMMENT '管理员标志(0-系统超级管理员，1-平台超级管理员，2-平台租户运营人员，3-平台普通管理员，4-租户超级管理员，5-租户普通账号)',\n" +
                    "  `Img` mediumblob COMMENT '账号头像',\n" +
                    "  `TenantId` int(4) NOT NULL DEFAULT '0' COMMENT '租户ID',\n" +
                    "  `Path` varchar(2000) NOT NULL DEFAULT ':-1:' COMMENT '从上到下创建路径',\n" +
                    "  PRIMARY KEY (`AccountId`),\n" +
                    "  KEY `RoleId` (`RoleId`),\n" +
                    "  KEY `TenantId` (`TenantId`)\n" +
                    ") ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COMMENT='账户';\n";
            String[] tableStrs = s.split(Pattern.quote(";\n"));
            for (String tableStr : tableStrs) {
                Map<String, Object> table = new HashMap<>();
                List<Map<String, String>> cols = new ArrayList<>();

                String[] colStrs = tableStr.trim().split(Pattern.quote("\n"));
                String tableName = colStrs[0].split(Pattern.quote("`"))[1];
                String tableCommentLine = colStrs[colStrs.length - 1];
                String tableComment = tableCommentLine.contains("'") ? tableCommentLine.split(Pattern.quote("'"))[1] : "";
                for (String colStr : colStrs) {
                    colStr = colStr.trim();
                    if (colStr.startsWith("`")) {
                        Map<String, String> col = new HashMap<>();
                        col.put("colName", colStr.substring(colStr.indexOf('`')+1, colStr.lastIndexOf('`')));
                        col.put("colType", colStr.split(" ")[1]);
                        if (colStr.contains("COMMENT")) {
                            String[] split = colStr.split("'");
                            col.put("colComment", split[split.length-2]);
                        } else {
                            col.put("colComment", "");
                        }
                        cols.add(col);
                    }
                }

                table.put("name", tableName);
                table.put("comment", tableComment);
                table.put("cols", cols);
                tables.add(table);
            }

            context.put("tables", tables);


//            StringWriter sw = new StringWriter();
            FileWriter fw = new FileWriter("xx.structure.html");
            template.merge(context, fw);
            fw.flush();
            fw.close();
//            System.out.println(sw.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
